﻿#include "ssInvokeInfo.h"
#include <algorithm>


namespace StarSeeker
{

ssInvokeInfo::ssInvokeInfo()
	: m_enableInvokeRecord(false), m_lastRecordTime(0)
{
	SS_MEMZERO(&m_total, sizeof(InvokeRecord))
}

void ssInvokeInfo::RecordInfo(u32 id, i64 tsEnd, i64 tsBegin)
{
	i64 ms = tsEnd - tsBegin;
	HASH_MAP<u32, InvokeRecord>::iterator itr = m_invokeInfo.find(id);
	if (itr == m_invokeInfo.end())
	{
		InvokeRecord qi = { id, 1, ms, 0 };
		m_invokeInfo[id] = qi;
	}
	else
	{
		itr->second.count++;
		itr->second.time += ms;
	}
	m_total.count++;
	m_total.time += ms;
	if (m_lastRecordTime == 0)
	{
		m_lastRecordTime = tsEnd;
	}
}

void ssInvokeInfo::ComputeRate()
{
	if (m_enableInvokeRecord)
	{
		//i64 nowSec = ssTime::GetTimeNow().i64p;
		//i64 diff = nowSec - m_last_invoke_info_time;
		//m_last_invoke_info_time = nowSec;
		m_infoOrder.clear();
		for (auto& itr : m_invokeInfo)
		{
			if (itr.second.count == 0)
				continue;

			itr.second.vap = itr.second.time / itr.second.count;
			m_infoOrder.push_back(itr.second);
			itr.second.count = 0;
			itr.second.time = 0;
			itr.second.vap = 0;
		}
		std::sort(m_infoOrder.begin(), m_infoOrder.end(), [](InvokeRecord& a, InvokeRecord& b) {
			return b.vap < a.vap;
		});
		if (!m_infoOrder.empty())
		{
			m_total.vap = m_total.time / m_total.count;
			//f32 qps = (f32)m_total.count / ((f32)m_total.time / 1000.0f);
		}
	}
}

}
